<?php
	class BaseDataAccess{
		/**
		* Link to DB connection
		*/
		private $link = '';
		/**
		* Default table name
		*/
		protected $_default_table_name = ''; 
		
		/**
		* Constructor - open mysql link
		*/
		public function __construct(){
			$classname = get_class($this);
			if (!isset($GLOBALS['db_'.$classname])){
				$this->link = mysql_connect(constant('DB_SERVER'), constant('DB_USER'), constant('DB_PASSWORD'));
				if ($this->link){
					mysql_select_db(constant('DB_NAME'), $this->link);
					mysql_set_charset('utf8');
				}
				$GLOBALS['db_'.$classname] = $this->link;	
			} else {
			    $this->link = $GLOBALS['db_'.$classname];
			}
		}
		/**
		 * Process where query as array and generates sql
		 */
		private function generateSqlForWhere($where){
			$result = $where;	
			if (is_array($where) && count($where) != 0){
				$where_clauses = array();
				foreach($where as $key => $value){
					$operation = "=";	
					if(substr($value, 0, 1) == '!'){
						$operation = "!=";
					} 
					if(is_string($value)){
						$value = "'".$value."'";
					}
					$where_clauses[] = "`".$key."`".$operation.$value;
				}
				$result = implode(' AND ', $where_clauses);
			}
			$result = ' WHERE '.$result;
			return $result;
		}
		
		/**
		* Process simple sql command (query)
		*/
		public function query($sql){
			if ($this->link){
				$return_data = array();
				$mysql_result = mysql_query($sql, $this->link);
				if($mysql_result && ($mysql_result !== true)){
					while($row = mysql_fetch_assoc($mysql_result)){
						$return_data[] = $row;
					}	
					return $return_data;
				} else return false;
			}
		}
		
		public function queryWithSelectedProperty($sql,$property){
			if ($this->link){
				$return_data = array();
				$mysql_result = mysql_query($sql, $this->link);
				if($mysql_result && ($mysql_result !== true)){
					while($row = mysql_fetch_array($mysql_result)){
						$return_data[] = $row[$property];
					}	
					return $return_data;
				} else return false;
			}
		}
		/**
		*  Generate table name for model
		*/
		public function get_table_name($table_name = ''){
			// choosing right table name in this order
			// 1. function parameter
			// 2. class variable
			// 3. defined constant for classname
			// 4. classname
			if($table_name == ''){
				if ($this->_default_table_name == ''){
					if (defined('tb_'.get_class($this))){
						$table_name = constant('tb_'.get_class($this));	
					} else {
						$table_name = 'tb_'.get_class($this);	
					}
				} else {
					$table_name = $this->_default_table_name;
				} 
			}	
			return $table_name;
		}
		/**
		*	Insert data to default table
		*/
		public function insert($in_data, $table_name = ''){
			// generate table name
			$table_name = $this->get_table_name($table_name);
			// format input array to keys
			$keys = '(`'.implode('`, `',array_keys($in_data)).'`)';
			// format input array to values
			$values = "('".implode("', '",array_values($in_data))."')";
			// finnaly glue up the sql
			$sql = 'INSERT INTO '.$table_name.' '.$keys.' VALUES '.$values;
			// and call it
			general::debug('sql insert query', $sql);
			return mysql_query($sql, $this->link);
		}
		
		/**
		* 	Select data from default table
		*/
		public function select($keys = array(), $table_name = '', $where = '', $limit = '', $order = ''){
			// if $keys is not string, or empty string, or empty array then select all
			if ((!is_string($keys) || $keys == '') && (!is_array($keys) || count($keys) == 0)){
				$keys = '*';
			} else if(is_array($keys)){
				// if it's array process it
				$keys = implode(', ', $keys);
			}
			
			// generate table name
			$table_name = $this->get_table_name($table_name);
			
			$sql = 'SELECT '.$keys.' FROM '.$table_name;
			// if there is where clause use it
			if ($where != ''){
				//if it's array process it
				$sql .= $this->generateSqlForWhere($where);
			}
			// if there is order clause, use it
			if ($order != ''){
				$sql .= ' ORDER BY '.$order;
			}
			// return result as array of associative array
			// if there is limit clause, use it
			if ($limit != ''){
				$sql .= ' LIMIT '.$limit;
			}
			// return result as array of associative array
			$return_data = array();
			general::debug('sql select query', $sql);
			$mysql_result = mysql_query($sql, $this->link);
			if($mysql_result){
				while($row = mysql_fetch_assoc($mysql_result)){
					$return_data[] = $row;
				}	
				return $return_data;
			} else return false;
		}
		
		/**
		* 	Update data in default table
		*/
		public function update($in_data, $table_name = '', $where = ''){
			// process data array to set string
			$data_set = array();
			foreach($in_data as $key => $value){
				if($value != ''){
					$data_set[] = "`".$key."`='".$value."'";
				}
			}
			$data_set = implode(', ', $data_set);
			
			// generate table name
			$table_name = $this->get_table_name($table_name);
			
			
			$sql = 'UPDATE '.$table_name.' SET '.$data_set;
			// if there is where clause use it
			if ($where != ''){
				//if it's array process it
				$sql .= $this->generateSqlForWhere($where);
			}
			general::debug('sql update', $sql);
			return mysql_query($sql, $this->link);
		}
		
		/**
		 * InsertUpdate - insert only if it's not in DB, otherwise update
		 */
		public function insertUpdate($in_data, $table_name = '', $where = ''){
			$result = $this->select('*', $tzable_name, $where, 1);
			if (!empty($result)){
				return $this->update($in_data, $table_name, $where);
			} else {
				return $this->insert($in_data, $table_name);
			}
			return $result;
		}

		/**
		* 	Select data from default table
		*/
		public function selectCount($table_name = '', $where = '', $limit = '', $order = ''){
			// generate table name
			$table_name = $this->get_table_name($table_name);
			
			$sql = 'SELECT COUNT(*) as `count` FROM '.$table_name;
			// if there is where clause use it
			if ($where != ''){
				//if it's array process it
				$sql .= $this->generateSqlForWhere($where);
			}
			// if there is order clause, use it
			if ($order != ''){
				$sql .= ' ORDER BY '.$order;
			}
			
			// if there is limit clause, use it
			if ($limit != ''){
				$sql .= ' LIMIT '.$limit;
			}
			// return result as array of associative array
			$return_data = array();
			general::debug('sql select count query', $sql);
			$mysql_result = mysql_query($sql, $this->link);
			if($mysql_result){
				$return_data = false;	
				if($row = mysql_fetch_assoc($mysql_result)){
					$return_data = $row['count'];
				}	
				return $return_data;
			} else return false;
		}

		/**
		 * Delete - deletes data from DB
		 */
		public function delete($table_name = '', $where = '', $limit = '', $order = ''){
			// generate table name
			$table_name = $this->get_table_name($table_name);
			
			$sql = 'DELETE FROM '.$table_name;
			// if there is where clause use it
			if ($where != ''){
				//if it's array process it
				$sql .= $this->generateSqlForWhere($where);
			}
			// if there is order clause, use it
			if ($order != ''){
				$sql .= ' ORDER BY '.$order;
			}
			
			// if there is limit clause, use it
			if ($limit != ''){
				$sql .= ' LIMIT '.$limit;
			}
			return mysql_query($sql, $this->link);
		}


		/**
		*	Destructor - close mysql link;
		*/
		public function __destruct(){
			/*$classname = get_class($this);
			if (isset($GLOBALS['db_'.$classname])){
				mysql_close($this->link);	
				unset($GLOBALS['db_'.$classname]);
			}*/
		}
	}
?>